<script name="DraggableImageUpload" setup>
import { uploadUrl } from '@/utils/request'// 请求url
import { getToken } from '@/utils/auth'
import { Check, Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref } from 'vue';


const props = defineProps({
  // 接受上传的文件类型（thumbnail-mode 模式下此参数无效）
  accept: {
    type: String,
    default: '.jpg,.jpeg,.png'
  },
  // 是否自动上传文件
  autoUpload: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: String,
    default: ''
  },
  uploadData: {
    type: Object,
    default: () => {}
  }
});

const token = ref();
onMounted(() => {
  token.value = getToken();
})


const emit = defineEmits(['update:modelValue']);
const curImage = computed({
  get () {
    return props.modelValue;
  },
  set (newValue) {
    emit('update:modelValue', newValue);
  }
});

// 图片预览
const handleImgPreview = (domClass) => {
  /*   showViewer.value = true
    previewList.value = [url] */
  const dom = document.getElementsByClassName(domClass);
  dom[0].firstElementChild.click(); // 调用 el-image 的预览方法
}

// 删除图片
const onImageRemove = () => {
  curImage.value = ''
}

// 上传前校验
const beforeImgUpload = rawFile => {
  let types = ['image/jpeg', 'image/jpg', 'image/png'];
  const size = rawFile.size
  const isImage = types.includes(rawFile.type);
  const isLt5M = size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage('请上传jpeg、jpg、png类型的图片', {
      type: 'error'
    });
    return false;
  } else if (!isLt5M) {
    ElMessage('上传图片大小不能超过5MB', {
      type: 'error'
    });
    return false
  }
  return true;
};

// 上传成功,给图片加前缀，防止切换时图片不显示
function handleImgSuccess (response, file, fileList) {
  console.log(response, file, fileList)
  curImage.value = response.data.url
}

</script>

<template>
  <div class="draggable_image_upload">
    <!-- 使用element-ui el-upload自带样式 -->
    <ul class="el-upload-list el-upload-list--picture-card" v-if="curImage">
      <li class="el-upload-list__item is-success animated">
        <el-image class="originalImg" fit="contain" :src="curImage" :preview-src-list="[curImage]" />
        <!--  <el-icon>
            <Close />
          </el-icon> -->
        <label class="el-upload-list__item-status-label">
          <el-icon class="el-icon--upload-success el-icon--check">
            <Check />
          </el-icon>
        </label>
        <span class="el-upload-list__item-actions">
          <!-- 预览    -->
          <span class="el-upload-list__item-preview" @click="handleImgPreview('originalImg')">
            <el-icon>
              <ZoomIn />
            </el-icon>
          </span>
          <!-- 删除    -->
          <span class="el-upload-list__item-delete" @click="onImageRemove(curImage)">
            <el-icon>
              <Delete />
            </el-icon>
          </span>
        </span>
      </li>
    </ul>
    <!-- 上传组件 -->
    <el-upload
        v-else
        :file-list="[{
          url: curImage,
        }]"
        :action="uploadUrl"
        list-type="picture-card"
        :accept="accept"
        :show-file-list="false"
        :before-upload="beforeImgUpload"
        :on-success="handleImgSuccess"
        :data="uploadData"
        :headers="{
        'authorization-business': token
      }"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<style scoped lang="scss">
.box-uploader{
  display: flex;
}
.originalImg{
  width: 100%;
}
</style>